package com.qiqidream.admin.security.login;

import com.qiqidream.admin.security.entity.SecurityUser;
import com.qiqidream.admin.system.service.UserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 自定义认证处理
 * @author QiQiDream
 * @since 2019/11/18 9:58
 */
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Resource
    UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        SecurityUser securityUser = (SecurityUser) userService.loadUser(userName);

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean isValid = passwordEncoder.matches(password, securityUser.getPassword());

        // 验证密码
        if (!isValid) {
            throw new BadCredentialsException("密码错误！");
        }

        return new UsernamePasswordAuthenticationToken(securityUser, password, securityUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
